<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="时间范围" prop="datePicker">
              <el-date-picker v-model="datePicker" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" @change="changeTimer" />
            </el-form-item>
            <el-form-item label="userId" prop="userId">
              <el-input v-model="queryParams.userId" placeholder="请输入userId" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="广告id" prop="promotionId">
              <el-input v-model="queryParams.promotionId" placeholder="请输入广告id" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="推广链接id" prop="referralLinkId">
              <el-input v-model="queryParams.referralLinkId" placeholder="请输入推广链接id" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item label="回传标记" prop="backFlag">
              <el-select v-model="queryParams.backFlag" clearable placeholder="请选择回传标记">
                <el-option v-for="(item, key) in status" :key="key" :value="item.code" :label="item.name"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['oce:iaaReturnRecord:list']">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery" v-hasPermi="['oce:iaaReturnRecord:list']">重置</el-button>
              <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oce:iaaBack:export']">导出</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <listView :list="sum" />
      <el-table v-loading="loading" :data="materialEverydayCensusList" @sort-change="sortChangeHandel" @selection-change="handleSelectionChange">
        <el-table-column label="链接id" prop="referralLinkId" minWidth="150"></el-table-column>
        <el-table-column label="userId" prop="userId" minWidth="150"></el-table-column>
        <el-table-column label="广告id" prop="promotionId" minWidth="150"></el-table-column>
        <el-table-column label="激励广告点击次数IPU" prop="advertNum" minWidth="120"></el-table-column>
        <el-table-column label="激励广告收入ARPU" prop="ecpmCost" minWidth="120">
          <template #default="{ row }"> {{ (row.ecpmCost / 1000).toFixed(5) }}元 </template>
        </el-table-column>
        <el-table-column label="平均eCPM" prop="avgEcpm" minWidth="120"></el-table-column>
        <el-table-column label="最大eCPM" prop="maxEcpm" width="120"></el-table-column>
        <el-table-column label="系统平台" prop="devicePlatform" width="90"></el-table-column>
        <el-table-column label="回传标记" prop="backFlag" width="90">
          <template #default="{ row }">
            <span>
              {{
                status.find((at) => {
                  return at.code == row.backFlag;
                })?.name
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="回传状态" prop="reportBackStatus" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.reportBackStatus === 0" key="el-tag-1" type="primary">无需上报</el-tag>
            <el-tag v-else-if="row.reportBackStatus === 1" key="el-tag-2" type="success">上报成功</el-tag>
            <el-tag v-else-if="row.reportBackStatus === 2" key="el-tag-3" type="danger">上报失败</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="广告回传时间" prop="backTime" minWidth="180"></el-table-column>
        <el-table-column label="用户买入时间" prop="userRegisterTime" minWidth="180"></el-table-column>
        <el-table-column label="备注" prop="remark" minWidth="180"></el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="100" class-name="small-padding fixed-width">
          <template #default="{ row }">
            <el-button
              link
              v-if="row.reportBackStatus !== 1"
              type="primary"
              icon="RefreshRight"
              @click="handleReportIaaBack(row)"
              v-hasPermi="['oce:iaaBack:reportIaaBack']"
              >手动上报</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="MaterialEverydayCensus" lang="ts">
import { GetIaaBackList, reportIaaBack } from '@/api/oce/iaaReturnRecord';
import { AdvertiserEverydayCostVO } from '@/api/oce/iaaReturnRecord/types';
import { formatYmd, formatPrice } from '@/utils';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const materialEverydayCensusList = ref<AdvertiserEverydayCostVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const status = ref([
  {
    name: '不计算',
    code: '-1'
  },
  {
    name: '是',
    code: '1'
  },
  {
    name: '否',
    code: '0'
  }
]);

const queryFormRef = ref<ElFormInstance>();
const data = reactive<PageData<AdvertiserEverydayCostVO, AdvertiserEverydayCostVO>>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    thatdayTimestamp: undefined,
    thatdayDate: undefined,
    cost: undefined,
    thatdayTotalAmount: undefined,
    thatdayPaidUseNum: undefined,
    gamePayCount: undefined,
    iaaTotalAmount: undefined,
    iaaDividendAmount: undefined,
    thatdayDividendAmount: undefined,
    thatdayProfitAmount: undefined,
    iaaRegisterTotalAmount: undefined,
    iaaRegisterDividendAmount: undefined,
    extRecoveryRate: undefined,
    convert: undefined,
    convertCost: undefined,
    returnRate: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    dramaTitle: undefined,
    startDate: undefined,
    endDate: undefined,
    createName: undefined,
    userId: undefined,
    referralLinkId: undefined,
    params: {}
  }
});

const { queryParams, form, rules } = toRefs(data);
const datePicker = ref<any>('');
const sum = ref([]);

/** 查询巨量素材每日数据统计列表 */
const getList = async () => {
  loading.value = true;
  const res = await GetIaaBackList(queryParams.value);
  materialEverydayCensusList.value = res.rows;
  sum.value = res.sum || [];
  total.value = res.total;
  loading.value = false;
};

const sortChangeHandel = ({ order, prop }) => {
  queryParams.value.orderByColumn = prop;
  queryParams.value.isAsc = order === 'ascending' ? 'asc' : 'desc';
  getList();
};

const changeTimer = (e) => {
  queryParams.value.startDate = e ? formatYmd(e[0]) : '';
  queryParams.value.endDate = e ? formatYmd(e[1]) : '';
};

/** 手动上报 */
const handleReportIaaBack = async (row?: any) => {
  await proxy?.$modal.confirm('是否手动上报？');
  await reportIaaBack(row?.iaaEcpmBackId);
  getList();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  datePicker.value = ['', ''];
  queryParams.value.startDate = '';
  queryParams.value.endDate = '';
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: AdvertiserEverydayCostVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    '/oce/iaaBack/export',
    {
      ...queryParams.value
    },
    `iaa回传记录.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
